#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <string.h>
#include <sys/shm.h>
#include<pthread.h>

#include "alg.8-0-shmdata.h"


unsigned long turn;
pthread_t T[2];
int flag[2];

void* runner(void* arg){
    struct shared_struct * shared = (struct shared_struct *)arg;
    
    
    int index = ((pthread_self() == T[0]) ? 0 : 1);

    printf("im %d\n", index);

    


    while (1) {

        flag[index] = 1;
        turn = 1 - index;
        while(flag[1 - index] && turn == 1 - index);


        
        while (shared->written == 0) {
            sleep(1); /* message not ready, waiting ... */
        }
        printf("read thread turn is %d\n", index);
        printf("%*sYou wrote: %s\n", 30, " ", shared->mtext);
        shared->written = 0;

        flag[index] = 0;
        if (strncmp(shared->mtext, "end", 3) == 0) {
            break;
        }
    } /* it is not reliable to use shared->written for process synchronization */
}

int main(int argc, char *argv[])
{
    void *shmptr = NULL;
    struct shared_struct *shared;
    int shmid;
    key_t key;
 
    sscanf(argv[1], "%x", &key);
    printf("%*sshmread: IPC key = %x\n", 30, " ", key);
    
    shmid = shmget((key_t)key, TEXT_NUM*sizeof(struct shared_struct), 0666|PERM);
    if (shmid == -1) {
        ERR_EXIT("shread: shmget()");
    }

    shmptr = shmat(shmid, 0, 0);
    if(shmptr == (void *)-1) {
        ERR_EXIT("shread: shmat()");
    }
    printf("%*sshmread: shmid = %d\n", 30, " ", shmid);    
    printf("%*sshmread: shared memory attached at %p\n", 30, " ", shmptr);
    printf("%*sshmread process ready ...\n", 30, " ");
    
    

    flag[0] = 0;
    flag[1] = 0;

    turn = 0;

    pthread_create(T, NULL,runner,shmptr);
    pthread_create(T + 1, NULL,runner,shmptr);

    printf("create ready \n");

    printf("%ld\n", T[0]);
    printf("%ld\n", T[1]);

    pthread_join(T[0], NULL);
    pthread_join(T[1], NULL);


    printf("join ready\n");

   if (shmdt(shmptr) == -1) {
        ERR_EXIT("shmread: shmdt()");
   }
 
    sleep(1);
    exit(EXIT_SUCCESS);
}
